package javase.reflect;

import org.junit.Before;
import org.junit.Test;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * Java反射获取Request请求中的参数并封装到指定的JavaBean
 * User: Realfighter
 * Date: 2014/11/2
 * Time: 11:35
 */
public class JavaBeanToMap {


    private JavaBean user;

    @Before
    public void setUp() {
        user = new JavaBean();
        user.setName("Realfighter");
        user.setSex("male");
    }

    @Test
    public void testJavaBeanToMap() {
        Map<String, String> map = packParams(user);
        System.out.println(map);//{sex=male, name=Realfighter}
    }

    @Test
    public void testMapToXmlStr() {
        Map<String, String> map = packParams(user);
        System.out.println(buildXmlStr(map));
        /**
         * 输出结果：
         <?xml version="1.0" encoding="UTF-8"?>
         <root>
             <sex>male	</sex>
             <name>Realfighter	</name>
         </root>
         */
    }

    /**
     * 将指定的对象转为Map
     *
     * @param obj
     * @return Map<String,String>
     * @Title: packParams
     * @author Realfighter
     */
    public static Map<String, String> packParams(Object obj) {
        Map<String, String> resultMap = new HashMap<String, String>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true); // 设置属性可以访问
            String key = field.getName();// 获取属性名
            String value = "";// 获取属性的值
            try {
                value = (String) field.get(obj);
            } catch (IllegalArgumentException e) {
                continue;
            } catch (IllegalAccessException e) {
                continue;
            }
            resultMap.put(key, value);
        }
        return resultMap;
    }

    /**
     * 构造xml信息
     *
     * @param map
     * @return String
     * @throws
     * @Title: buildXmlStr
     * @author Realfighter
     */
    public static String buildXmlStr(Map<String, String> map) {
        StringBuffer xmlStr = new StringBuffer();
        Object[] keyArray = map.keySet().toArray();
        String[] keys = new String[map.keySet().size()];
        xmlStr.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        xmlStr.append("<root>\n");
        for (int i = 0; i < keyArray.length; i++) {
            keys[i] = keyArray[i].toString();
            xmlStr.append("\t<" + keys[i] + ">");
            xmlStr.append((String) map.get(keys[i]));
            xmlStr.append("\t</" + keys[i] + ">\n");
        }
        xmlStr.append("</root>");
        return xmlStr.toString();
    }

}

class JavaBean {
    String name;//姓名
    String sex;//性别

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}
